<template>
  <div class="reg">
    <el-card class="box-card">
      <div class="reg-title"></div>
      <el-form :model="user" :rules="rules" ref="form">
        <el-form-item prop="username">
          <el-input
            v-model="user.username"
            prefix-icon="el-icon-user"
            placeholder="用户名"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="user.password"
            prefix-icon="el-icon-lock"
            placeholder="密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input
            v-model="user.repassword"
            prefix-icon="el-icon-lock"
            placeholder="再次输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reg">注册</el-button>
        </el-form-item>
        <el-link @click="$router.push('/login')" :underline="false">已有账号? 去登录</el-link>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { regAPI } from '@/api/user'
export default {
  name: 'MyReg',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === this.user.password) {
        callback()
      } else {
        callback(new Error('两次密码不一致'))
      }
    }
    return {
      user: {
        username: '',
        password: '',
        repassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        repassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    reg() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log('验证通过')
        const { data: res } = await regAPI(this.user)
        console.log(res)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$refs.form.resetFields() // 重置表单
          this.$router.push('/login')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.reg {
  height: 100%;
  background: url('@/assets/images/login_bg.jpg') no-repeat;
  background-size: cover;
}
.el-card {
  width: 400px;
  /* height: 310px; */
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.reg-title {
  height: 40px;
  background: url('@/assets/images/login_title.png') top center no-repeat;
}
.el-button {
  width: 100%;
}
</style>
